package org.eclipse.xtext.generator.extended;

import static com.google.common.collect.Lists.newArrayList;

import java.util.List;

import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.mwe2.runtime.workflow.IWorkflowContext;
import org.eclipse.xtext.generator.GeneratorComponent;
import org.eclipse.xtext.generator.IFileSystemAccess;

public class Generator2Component extends GeneratorComponent {

	private List<String> slotNames2 = newArrayList();
	private ResourceSet resourceSet;

	@Override
	public void addSlot(java.lang.String slot) {
		this.slotNames2.add(slot);
		super.addSlot(slot);
	}

	@Override
	public void invoke(IWorkflowContext ctx) {
		for (String slot : slotNames2) {
			Object object = ctx.get(slot);
			if (object == null) {
				throw new IllegalStateException("Slot '"+slot+"' was empty!");
			}
			if (object instanceof Iterable) {
				Iterable<?> iterable = (Iterable<?>) object;
				for (Object object2 : iterable) {
					if (!(object2 instanceof Resource)) {
						throw new IllegalStateException("Slot contents was not a Resource but a '"+object.getClass().getSimpleName()+"'!");
					}
					Resource r = (Resource) object2;
					resourceSet = r.getResourceSet();
				}
			} else if (object instanceof Resource) {
				Resource r = (Resource) object;
				resourceSet = r.getResourceSet();
			} else {
				throw new IllegalStateException("Slot contents was not a Resource but a '"+object.getClass().getSimpleName()+"'!");
			}
		}

		super.invoke(ctx);
	}

	@Override
	public void postInvoke() {
		IGenerator2 instance = (IGenerator2) getCompiler();
		IFileSystemAccess fileSystemAccess = getConfiguredFileSystemAccess();

		instance.doGenerate(resourceSet, fileSystemAccess);
	}

}
